package net.huashitong.ssydt.provider.wxpay.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import net.huashitong.ssydt.provider.wxpay.config.WeChatPayConfig;
import net.huashitong.ssydt.provider.wxpay.entity.WeChatPayRequestModel;
import net.huashitong.ssydt.provider.wxpay.service.WeChatPaySuccessService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 微信支付回调
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.08.16
 */
@Controller
@RequestMapping("/wechat/pay")
public class WeChatPayController {

    private WeChatPayConfig weChatPayConfig;

    private WeChatPaySuccessService weChatPaySuccessService;

    public WeChatPayController(WeChatPayConfig weChatPayConfig,
                               WeChatPaySuccessService weChatPaySuccessService) {
        this.weChatPayConfig = weChatPayConfig;
        this.weChatPaySuccessService = weChatPaySuccessService;
    }

    /**
     *
     * @param notifyData 支付结果通知的xml格式数据
     * @throws Exception
     */
    @RequestMapping("/notify")
    public void notifyUrl(@RequestBody String notifyData, HttpServletResponse response) throws Exception {
        WXPay wxpay = new WXPay(weChatPayConfig, WXPayConstants.SignType.MD5, weChatPayConfig.isUseSandbox());

        Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyData);  // 转换成map

        if (wxpay.isPayResultNotifySignatureValid(notifyMap)) {
            WeChatPayRequestModel model = new WeChatPayRequestModel(notifyMap);
            // 签名正确
            // 进行处理。
            // 注意特殊情况：订单已经退款，但收到了支付结果成功的通知，不应把商户侧订单状态从退款改成支付成功
            if ("SUCCESS".equals(model.getReturn_code())) {
                weChatPaySuccessService.paySuccess(model);
            } else {
                //即时到账支付失败
                sendToCFT("fail", response);
            }
            sendToCFT("success", response);
        } else {
            // 签名错误，如果数据里没有sign字段，也认为是签名错误
            sendToCFT("fail", response);
        }
    }

    private void sendToCFT(String msg, HttpServletResponse response) throws IOException {
        String strHtml = msg;
        PrintWriter out = response.getWriter();
        out.println(strHtml);
        out.flush();
        out.close();

    }

}
